package com.ml.mall.service.catalogue.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.NumberUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ml.mall.bean.req.catalogue.*;
import com.ml.mall.bean.res.catalogue.SysCatalogueProductQueryAllRes;
import com.ml.mall.bean.res.product.SysProductShopPageRes;
import com.ml.mall.bean.vo.catalogue.CatalogueProductPicUrlVo;
import com.ml.mall.entity.catalogue.SysCatalogue;
import com.ml.mall.entity.catalogue.SysCatalogueProduct;
import com.ml.mall.entity.deduct.SysADeduct;
import com.ml.mall.entity.sys.SysUser;
import com.ml.mall.entity.variant.SysProductVariant;
import com.ml.mall.entity.variant.SysProductVariantPic;
import com.ml.mall.enums.CommonEnum;
import com.ml.mall.exception.BizException;
import com.ml.mall.mapper.catalogue.SysCatalogueMapper;
import com.ml.mall.mapper.catalogue.SysCatalogueProductMapper;
import com.ml.mall.mapper.variant.SysProductVariantMapper;
import com.ml.mall.mapper.variant.SysProductVariantPicMapper;
import com.ml.mall.security.JwtUtil;
import com.ml.mall.service.catalogue.SysCatalogueProductService;
import com.ml.mall.service.coupon.SysCouponService;
import com.ml.mall.service.deduct.SysADeductService;
import com.ml.mall.service.shop.ShopService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author :pl
 * @version :1.0
 * @description :收藏目录添加产品实现类
 * @date :2021/5/26
 **/
@Service
@Slf4j
public class SysCatalogueProductServiceImpl extends ServiceImpl<SysCatalogueProductMapper, SysCatalogueProduct> implements SysCatalogueProductService {
    @Autowired
    private SysCatalogueProductMapper sysCatalogueProductMapper;
    @Autowired
    private SysProductVariantPicMapper sysProductVariantPicMapper;
    @Autowired
    private SysCatalogueMapper sysCatalogueMapper;
    @Autowired
    private ShopService shopService;
    @Autowired
    private SysADeductService sysADeductService;
    @Autowired
    private SysCouponService sysCouponService;

    /**
     * 实现收藏夹目录内产品的添加功能
     * 产品总个数不能超过24个，有重复的产品需要数量加一
     * @param dto
     * @return
     */
    @Override
    public int sysCatalogueProductAdd(SysCatalogueProductAddDto dto) {
        //传参catalogueId、variantId
        //能添加产品说明已经进入了收藏目录
        //判断是否收藏目录中已经存在该产品
        QueryWrapper<SysCatalogueProduct> checkRepeatProduct = new QueryWrapper<>();
        checkRepeatProduct.eq("catalogue_id",dto.getCatalogueId())
                .eq("variant_id",dto.getVariantId());
        SysCatalogueProduct productRepeatResult = sysCatalogueProductMapper.selectOne(checkRepeatProduct);
        log.info("该产品查找后的结果：{}",productRepeatResult);
        //找到了该产品，需要把该产品数量+1
        if (productRepeatResult!=null){
            Integer quality = productRepeatResult.getQuality();
            quality+=1;
            productRepeatResult.setQuality(quality);
            //执行单个产品数量+1操作
            int update = sysCatalogueProductMapper.updateById(productRepeatResult);
            log.info("存在该产品并数量+1。");
            return update;
        }
        //没有找到就创建新的子产品
        //根据catalogueId判断产品数量是否满24个,由于variantId不同可由一个字段判断
        QueryWrapper<SysCatalogueProduct> queryWrapperCount = new QueryWrapper<>();
        queryWrapperCount.eq("catalogue_id",dto.getCatalogueId());
        Integer productCount = sysCatalogueProductMapper.selectCount(queryWrapperCount);
        log.info("判断当前收藏夹是否已满24个产品:{}",productCount);
        //收藏夹已满24个产品
        if (productCount==24){
            throw new BizException(CommonEnum.INSERT_MAX_ERROR);
        }
        //未满24个产品，收藏目录中添加新产品；首先需要找到产品对应的图片地址并封装
        //通过variantId找到picUrl
        QueryWrapper<SysProductVariantPic> getPicUrl = new QueryWrapper<>();
        getPicUrl.eq("variant_id",dto.getVariantId())
                .orderByAsc("`index`")
                .last("limit 1");
        log.info("sql查询语句：{}",getPicUrl.getSqlSelect());
        SysProductVariantPic productVariantPic = sysProductVariantPicMapper.selectOne(getPicUrl);
        log.info("找到的图片地址为：{}",productVariantPic);
        if (productVariantPic==null){
            throw new BizException(CommonEnum.SELECT_ERROR);
        }
        //将传入的数据进行封装
        SysCatalogueProduct sysCatalogueProduct = new SysCatalogueProduct();
        sysCatalogueProduct.setCatalogueId(dto.getCatalogueId())
                .setPicUrl(productVariantPic.getPicUrl())
                .setVariantId(dto.getVariantId());
        log.info("即将执行添加操作的封装类数据{}",sysCatalogueProduct.toString());
        int insert = sysCatalogueProductMapper.insert(sysCatalogueProduct);
        log.info("执行添加产品的结果{}",insert);
        if (insert==0){
            throw new BizException(CommonEnum.INSERT_ERROR);
        }
        return insert;
    }

    @Override
    public List<SysCatalogueProductQueryAllRes> sysCatalogueProductQueryAll() {
        //最终封装
        List<SysCatalogueProductQueryAllRes> listRes = new ArrayList<>();
        //jwt获取companyId
        Long companyId = JwtUtil.getCurrentUser().getCompanyId();
        //根据companyId获取sysCatalogue里面的所有信息
        QueryWrapper<SysCatalogue> queryByCompanyId = new QueryWrapper<>();
        queryByCompanyId.eq("company_id",companyId);
        List<SysCatalogue> catalogueList = sysCatalogueMapper.selectList(queryByCompanyId);
        //逐个获取catalogueId
        for (SysCatalogue sysCatalogue:catalogueList){
            //用于封装的对象
            SysCatalogueProductQueryAllRes res = new SysCatalogueProductQueryAllRes();
            //根据catalogueId统计收藏夹中产品个数
            QueryWrapper<SysCatalogueProduct> productCountWrapper = new QueryWrapper<>();
            productCountWrapper.eq("catalogue_id",sysCatalogue.getCatalogueId());
            productCountWrapper.eq("is_delete","0");
            Integer totalProduct = sysCatalogueProductMapper.selectCount(productCountWrapper);
            //根据catalogueId找到picUrl数据
            List<CatalogueProductPicUrlVo> picUrlList = sysCatalogueProductMapper.selectPicUrlList(sysCatalogue.getCatalogueId());
            log.info("picUrlList==={}",picUrlList);
            log.info("picUrlList==={}",totalProduct);
            //单个封装
            res.setCatalogueName(sysCatalogue.getCatalogueName())
                    .setId(sysCatalogue.getId())
                    .setCatalogueId(sysCatalogue.getCatalogueId())
                    .setTotalProduct(totalProduct)
                    .setPicUrlArr(picUrlList)
                    .setPrefferedType(sysCatalogue.getPrefferedType());
            //最终封装
            listRes.add(res);
        }
        return listRes;
    }

    @Override
    public List<SysProductShopPageRes> catalogueProductQueryList(CatalogueDto dto) {
        // 当前用户只能查询到自己的收藏夹
        SysUser currentUser = JwtUtil.getCurrentUser();
        List<SysProductShopPageRes> listItem = sysCatalogueProductMapper.selectCatalogueAllProduct(dto.getCatalogueId(),currentUser.getCompanyId());
        SysADeduct curDeduct = sysADeductService.getCurDeduct();
        listItem.stream().forEach(item->{
            item.changePrice(curDeduct);
        });
        List<SysProductShopPageRes> shopPageResList = shopService.recognizeShopHaveCoupponPageRes(listItem);

        return shopPageResList;
    }

    @Override
    public int editCatalogueVariant(SysCatalogueVariantEditDto dto) {
        SysCatalogueProduct sysCatalogueProduct = new SysCatalogueProduct();
        sysCatalogueProduct.setId(dto.getId());
        if(dto.getQuality() != null){
            sysCatalogueProduct.setQuality(dto.getQuality());
        }
        if(dto.getVariantId() != null){
            QueryWrapper<SysProductVariantPic> getPicUrl = new QueryWrapper<>();
            getPicUrl.eq("variant_id",dto.getVariantId())
                    .orderByAsc("`index`")
                    .last("limit 1");
            log.info("sql查询语句：{}",getPicUrl.getSqlSelect());
            SysProductVariantPic productVariantPic = sysProductVariantPicMapper.selectOne(getPicUrl);
            sysCatalogueProduct.setPicUrl(productVariantPic.getPicUrl());
            sysCatalogueProduct.setVariantId(dto.getVariantId());
        }
        sysCatalogueProductMapper.updateById(sysCatalogueProduct);
        return 0;
    }

    @Override
    public int delVariantFromCatelgogue(CatalogueDelVariantDto dto) {
        return sysCatalogueProductMapper.deleteById(dto.getId());
    }

    @Override
    public int editCatalogue(CatalogueEditDto dto) {
        //判断收藏夹是否属于当前用户
        SysUser currentUser = JwtUtil.getCurrentUser();
        SysCatalogue dbCatalogue = sysCatalogueMapper.selectById(dto.getId());
        if(dbCatalogue == null || !NumberUtil.equals(currentUser.getCompanyId(),dbCatalogue.getCompanyId())){
            return -1;
        }

        SysCatalogue sysCatalogue = new SysCatalogue();
        BeanUtil.copyProperties(dto, sysCatalogue);
        return sysCatalogueMapper.updateById(sysCatalogue);
    }

    @Override
    public int editCatalogueName(CatalogueNameEditDto dto){
        //判断收藏夹是否属于当前用户
        SysUser currentUser = JwtUtil.getCurrentUser();
        SysCatalogue dbCatalogue = sysCatalogueMapper.selectById(dto.getId());
        if(dbCatalogue == null || !NumberUtil.equals(currentUser.getCompanyId(),dbCatalogue.getCompanyId())){
            return -1;
        }

        SysCatalogue sysCatalogue = new SysCatalogue();
        BeanUtil.copyProperties(dto, sysCatalogue);
        return sysCatalogueMapper.updateById(sysCatalogue);
    }
}
